/**
 * @fileoverview Minerva core js
*/

// Namespace
minerva = {};
// Event url
minerva.evurl = '/evs?format=json';
// Google Ajax Api options

// Setup noops for firebug calls if it isn't installed
if (!window.console || !console.firebug) {
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
      "dirxml","group", "groupEnd", "time", "timeEnd", "count", "trace",
      "profile", "profileEnd"];
  window.console = {};
  for (var i = 0; i < names.length; ++i) {
    window.console[names[i]] = function() {};
    }
  }

if (google.gears) {
  $(function() {
    // On ready and Gears exists init Gears and TagCloud
    minerva.db = google.gears.factory.create('beta.database');
    minerva.db.open();
    // Real simple for now
    minerva.db.execute('create table if not exists Workers' +
        ' (id varchar(255), url varchar(255), job varchar(255))');
  
    minerva.db.execute('create table if not exists NounEvents' +
        ' (pwun integer, path varchar(255), action varchar(255), creator varchar(255), created float, type varchar(255), title varchar(255))');
    minerva.db.execute('create table if not exists Filters' +
        ' (root varchar(255), types varchar(255), authors varchar(255), tags varchar(255))');

    minerva.timer = google.gears.factory.create('beta.timer');
    minerva.wp = google.gears.factory.create('beta.workerpool');

    minerva.wp.onmessage = function(text, sid) {
      console.log('Main worker pool got message:', text, sid);
      if (sid == minerva.evsync_id) {
        // Message from evsync, display in jGrowl
        $.jGrowl(text);
        }
      else if (sid == minerva.navclouder_id) {
        // Message from navclouder, display in TagCloud
        var result = JSON.parse(text);
        var parent_path = result[0];
        var cloud_data = result[1];
        var tags = cloud_data[0];
        var pathmap = cloud_data[1];

        var tc = TagCloud.create();
        for (var tagname in tags) {
          tc.add(tagname, tags[tagname], pathmap[tagname]);
          }
        tc.loadEffector('CountSize').base(20).range(10);
        tc.setup('navcloud');
        }
      else if (sid == minerva.filterer_id) {
        // Message from filterer, display in Mercury
        // $('.filter_results').html(text);
        var result = JSON.parse(text);
        console.log('Got filter results:', result);
        }
      };

    minerva.evsync_id = minerva.wp.createWorkerFromUrl(
        '/javascript/evsync.min.js');
    minerva.navclouder_id = minerva.wp.createWorkerFromUrl(
        '/javascript/navclouder.min.js');
    minerva.filterer_id = minerva.wp.createWorkerFromUrl(
        '/javascript/filterer.min.js');

    // TODO: Control+e is listened for in wikipedia, change to something else
    $(document).bind('keydown', 'Ctrl+e', function(){
      // Sync events
      minerva.wp.sendMessage(minerva.evurl, minerva.evsync_id);
      });

    // Get the current path
    console.log('using path', location.pathname);
    minerva.wp.sendMessage(location.pathname, minerva.navclouder_id);
    });
  }


minerva.mercuryFilterChanged = function(e) {
  // Derive new query result and render
  console.log('input changed', e.target);
  var inputs = $('#mercury input');
  var params = {};
  for (var i=0; i<inputs.length; i++) {
    var inp = inputs.get(i);
    var param_name = inp.id.slice(5);
    params[param_name] = inp.value;
    }

  var spec = JSON.stringify(params);
  minerva.wp.sendMessage(spec, minerva.filterer_id);
  };


minerva.mercuryResultClicked = function(e) {
  var span = e.target;
  console.log('span got clicked', span, span.id);
  $('span.selected').toggleClass('selected');
  $(span).toggleClass('selected');

  // Now - look for a widget to insert this into
  if (minerva.infocus) {
    var directive = '\n.. noun:: ' + span.id + '\n';
    minerva.infocus.value += directive;
    }
  };


minerva.mercuryResultDblClicked = function(e) {
  // Take them where they want to go
  var span = e.target;
  console.log('span got dbl clicked', span, span.id);
  $('span.selected').toggleClass('selected');
  $(span).toggleClass('selected');
  location.href = location.protocol + '//' + location.host + span.id;
  };
